
jQuery(document).ready(function($) {
  
  var baseURL = GLOBALPATH.site_url;
   $.getJSON(baseURL+'/api/traiplers_rest/all_traiplers_titles_and_ids/', {param1: 'value1'}, function(json, textStatus) {
       /*optional stuff to do after success */
       console.log(json);
       var traiplers = json.message;
       initLiveSearch(traiplers);
   });
   
 
 function initLiveSearch(traiplers){
   // constructs the suggestion engine
   var states = new Bloodhound({
     //datumTokenizer: Bloodhound.tokenizers.whitespace('title'),
     datumTokenizer: function(d) {
      var tk = Bloodhound.tokenizers.whitespace(d.title+d.description);
         return tk;
       },
     queryTokenizer: Bloodhound.tokenizers.whitespace,
     limit: 20,
     // `states` is an array of state names defined in "The Basics"
     local: traiplers
   });
    
   // kicks off the loading/processing of `local` and `prefetch`
   states.initialize();
    
    
    
   $('.typeahead').typeahead({
     hint: true,
     highlight: true,
     minLength: 1
   },
   {
     name: 'states',
     displayKey: 'title',
     // `ttAdapter` wraps the suggestion engine in an adapter that
     // is compatible with the typeahead jQuery plugin
     source: states.ttAdapter(),
     templates: {
         empty: [
           '<div class="empty-message">',
           'Nessun risultato',
           '</div>'
         ].join('\n'),
         suggestion: function(traipler){
            return '<p>'+traipler.title+'</p>'; 
          
         }
       }
       
   })
   .on('typeahead:opened', onOpened)
    .on('typeahead:selected', onAutocompleted)
    .on('typeahead:autocompleted', onSelected)
    
    //$(".twitter-typeahead, .typeahead").slideDown();
 
 $(".typeahead.tt-input")
 .focus(function(){
   $(".typeahead,.tt-query,.tt-hint").addClass('active')
 })
 .blur(function(){
  $(".typeahead,.tt-query,.tt-hint").removeClass('active')
 })
 
 
    function onOpened($e) {
        console.log('opened');
        
    }
     
    function onAutocompleted($e, datum) {
        console.log('autocompleted');
        console.log(datum);
        if(datum.link)
        location.href = datum.link
    }
     
    function onSelected($e, datum) {
        console.log('selected');
        console.log(datum);
        
    }
 }
 
 $('#traipler_topbar .typeahead').show();
 
  
 
 
});


 
 